<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/
jimport ( 'joomla.application.component.view' );

require_once (JPATH_COMPONENT . DS . 'asset' . DS . 'XMLExportHelper.php');

class JAJobBoardViewJAXMLExport extends JAView {
	/**
	 * $_id;
	 * 
	 * */
	var $_id;
	/**
	 * $_data;
	 * 
	 * */
	var $_data;
	/**
	 * Constructor
	 */
	function __construct() {
		parent::__construct ();
		$this->_id = JRequest::getVar ( 'cid', 0, '', 'array' );
		$this->_id = ( int ) $this->_id [0];
	}
	/**
	 * Display the view
	 */
	function display($tmpl = null) {
		?><!-- 
		 -->
		 <div style="width: 100%; position: relative;">
		 	<div style="margin-left: 17.5%; border: 1px solid #999999; padding:  4px;">
		 		<img border="0" alt="Tooltip" src="<?php global $mainframe; echo $mainframe->getSiteURL()?>/includes/js/ThemeOffice/warning.png"/>
		 		<?php echo JText::_('XML TOOL NOTICE MESSAGE')?>
		 	</div>
		 
		 </div>
		 <?php
		$tab = JRequest::getVar ( "tab", "feeds" );
		$task = JRequest::getVar ( "task", "list" );
		switch ($tab) {
			case "feeds" :
				{
					switch ($task) {
						case "edit" :
						case "add" :
							$this->displayAddItems ();
							break;
						default :
							$this->displayListItems ();
					}
				}
				break;
			
			case "schemas" :
				{
					switch ($task) {
						
						case "edit" :
						case "add" :
							$this->displayAddSchemas ();
							break;
						case "configxml" :
							$this->displayConfigXML ();
							break;
						default:
							$this->displayListSchemas ();							
					}
				}
				break;
		
		}
		
		parent::display ( $tmpl );
	}
	
	/**
	 * Generate selectbox for feed categories
	 * @param int $selectID selected id
	 * @return string selectbox in html format
	 * */
	
	function getSelectboxSchema($selectID) {
		$db = & JFactory::getDBO ();
		$db->setQuery ( "SELECT SchemaID, SchemaName FROM #__ja_xml_schemas" );
		$groups = $db->loadObjectList ();
		if (1) {
			foreach ( $groups as $value => $text ) {
				$groupHTML [] = JHTML::_ ( 'select.option', $text->SchemaID, $text->SchemaName );
			}
			
			$lists = JHTML::_ ( 'select.genericlist', $groupHTML, 'SchemaID', 'class="inputbox" size="1" onchange="form.submit();"', 'value', 'text', $selectID );
		}
		return $lists;
	}
	
	/**
	 * Generate selectbox for feed categories
	 * @param int $selectID selected id
	 * @return string selectbox in html format
	 * */
	
	function getSelectboxJobType($selectID) {
		$db = & JFactory::getDBO ();
		$db->setQuery ( "SELECT value, text FROM #__ja_codes WHERE field_id = 'ja_jobs_job_type' ORDER BY value " );
		$groups = $db->loadObjectList ();
		$groupHTML [] = JHTML::_ ( 'select.option', "", "--All--" );
		if (1) {
			foreach ( $groups as $value => $text ) {
				$groupHTML [] = JHTML::_ ( 'select.option', $text->value, $text->text );
			}
			
			$lists = JHTML::_ ( 'select.genericlist', $groupHTML, 'search_type', 'class="inputbox" size="1"', 'value', 'text', $selectID );
		}
		return $lists;
	}
	
	/**
	 * Get selectbox data in html string
	 * @param string $name Name of combobox
	 * @param int $id Value of option tag
	 * @param string $value Text in option tag
	 * @param int $selectID Value of selected option tag
	 * @return string $lists hmtl string present combobox.
	 * */
	function getComboboxData($name, $table, $selectID, $multiple=false){
		$db =& JFactory::getDBO();
		$selectID = explode(",", $selectID);
		$db->setQuery("SELECT id, name FROM {$table} WHERE parent_id = '0' ORDER BY name ASC");
		
		$groups = $db->loadAssocList();
		
		$groupHTML[] = JHTML::_('select.option', $text['id'], "--All--");
		
		foreach ($groups as $k1=>$text){			
			$groupHTML[] = JHTML::_('select.option', $text['id'], "&nbsp;&nbsp;&nbsp;".$text['name']);
				$db->setQuery("SELECT id, name FROM {$table} WHERE parent_id = '{$text[id]}' ORDER BY name ASC");
				$groups1 = $db->loadAssocList();
				foreach ($groups1 as $k2=>$text1){
					$groupHTML[] = JHTML::_('select.option', $text1['id'], "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;".$text1['name']);
				}
		}
		if(!$multiple)
			$lists = JHTML::_('select.genericlist', $groupHTML, $name, 'class="inputbox"', 'value', 'text', $selectID);
		else
			$lists = JHTML::_('select.genericlist', $groupHTML, $name, 'class="inputbox" multiple style="height:150px" ', 'value', 'text', $selectID);
		
		return $lists;
	}
	
	/**
	 * Display List of items
	 */
	function displayListItems() {
		global $mainframe, $option;
		
		$usergroup = JRequest::getVar ( 'usergroup', 'admin' );				
		// Get model
		$model = & $this->getModel ();
		// Filter proceess
		$option_1 = $option . '.jaxmlexport';
		$search = $mainframe->getUserStateFromRequest ( "$option_1.search", 'search', '', 'string' );
		$lists ['search'] = JString::strtolower ( $search );
		$lists ['filter_order'] = JRequest::getVar ( 'filter_order', 'u.FeedID' );
		$lists ['filter_order_Dir'] = $mainframe->getUserStateFromRequest ( $option_1 . '.filter_order_Dir', 'filter_order_Dir', '', 'word' );
		$lists ['option'] = $option;
		$filter_state = $mainframe->getUserStateFromRequest ( $option_1 . '.filter_state', 'filter_state', '', 'word' );
		$lists ['state'] = JHTML::_ ( 'grid.state', $filter_state );
		$usertype = '';
		$usertype = $mainframe->getUserStateFromRequest ( $option_1 . $usergroup . '.usertype', 'usertype', '', 'string' );
		
		// Get feed categories
		$db = & JFactory::getDBO ();
		$db->setQuery ( "SELECT SchemaID, SchemaName FROM #__ja_xml_schemas" );
		$groups = $db->loadObjectList ();
		if (1) {
			$groupHTML [] = JHTML::_ ( 'select.option', '', JText::_ ( 'Select Schema...' ) );
			if (is_array($groups))
				foreach ( $groups as $value => $text ) {
					$groupHTML [] = JHTML::_ ( 'select.option', $text->SchemaID, $text->SchemaName );
				}
			$lists ['group'] = JHTML::_ ( 'select.genericlist', $groupHTML, 'usertype', 'class="inputbox" size="1" onchange="form.submit()"', 'value', 'text', $usertype );
		}
		
		// get data items
		$items = $model->getItems ( $usertype );
		// Assign variable
		$pagination = & $this->get ( 'Pagination' );
		$this->assignRef ( 'lists', $lists );
		$this->assignRef ( 'items', $items );
		$this->assignRef ( 'usergroup', $usergroup );
		$this->assignRef ( 'pagination', $pagination );
	}
	
	/**
	 * Display add schema form
	 * */
	function displayAddSchemas() {		
		// Get model and data
		$model = & $this->getModel ();
		$this->assignRef ( "data", $model->getSchemaItem () );
	}
	
	/**
	 * Display add schema form
	 * */
	function displayConfigXML() {			
		
		// Get model and data for schema
		$model = & $this->getModel ();
		$schemadata = $model->getSchemaItem ();
		$this->assignRef ( "data", $schemadata );
		// Get schema details
		$schemadetails = $model->getSchemaDetails ();
		$this->assignRef ( "details", $schemadetails );
		
		// Get action and assign data
		$act = JRequest::getVar ( "act", "add" );
		switch ($act) {
			case "edit" :
				$title = "Edit ";
				break;
			case "add" :
				$title = "Insert new ";
				break;
			case "save" :
				$data = JRequest::get ( "post" );
				$id = $model->saveSchemaDetails ( $data );
				if ($id) {
					$msg = "Save data succesfull.";
					// Get schema details
					JRequest::setVar ( 'ElementID', $id );
					$schemadetails = $model->getSchemaDetails ();
					$this->assignRef ( "details", $schemadetails );
				} else
					$msg = "Error saving data.";
				break;
			case "delete" :
				if ($model->deleteSchemaDetails ()) {
					// Get schema details
					JRequest::setVar ( 'ElementID', 0 );
					$schemadetails = $model->getSchemaDetails ();
					$this->assignRef ( "details", $schemadetails );
					$msg = "Delete element succesfull";
				} else
					$msg = "This element have some child, you cannot delete it.";
				break;
		}
		$this->assignRef ( "msg", $msg );
		$this->assignRef ( "title", $title );
	}
	
	/**
	 * Build selectbox for XML structure ParentID
	 * */
	function buildSelectboxXMLStructure($SchemaID, $selectID) {
		$db = & JFactory::getDBO ();
		$groupHTML [] = JHTML::_ ( 'select.option', "0", "Root" );
		// Level 1
		$db->setQuery ( "SELECT ElementID, ElementName FROM #__ja_xml_schemas_details WHERE ParentID = '0' AND SchemaID = '{$SchemaID}'" );
		$groups = $db->loadObjectList ();
		foreach ( $groups as $value => $text ) {
			$groupHTML [] = JHTML::_ ( 'select.option', $text->ElementID, "&nbsp;&nbsp;&nbsp;" . $text->ElementName );
			// Level 2
			$db->setQuery ( "SELECT ElementID, ElementName FROM #__ja_xml_schemas_details WHERE ParentID = '$text->ElementID' AND SchemaID = '{$SchemaID}'" );
			$groups1 = $db->loadObjectList ();
			foreach ( $groups1 as $value1 => $text1 ) {
				$groupHTML [] = JHTML::_ ( 'select.option', $text1->ElementID, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $text1->ElementName );
				// Level 3
				$db->setQuery ( "SELECT ElementID, ElementName FROM #__ja_xml_schemas_details WHERE ParentID = '$text1->ElementID' AND SchemaID = '{$SchemaID}'" );
				$groups2 = $db->loadObjectList ();
				foreach ( $groups2 as $value2 => $text2 ) {
					$groupHTML [] = JHTML::_ ( 'select.option', $text2->ElementID, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $text2->ElementName );
					// Level 4
					$db->setQuery ( "SELECT ElementID, ElementName FROM #__ja_xml_schemas_details WHERE ParentID = '$text2->ElementID' AND SchemaID = '{$SchemaID}'" );
					$groups3 = $db->loadObjectList ();
					foreach ( $groups3 as $value3 => $text3 ) {
						$groupHTML [] = JHTML::_ ( 'select.option', $text3->ElementID, "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" . $text3->ElementName );
					}
				}
			}
		}
		
		return JHTML::_ ( 'select.genericlist', $groupHTML, 'ParentID', 'class="inputbox" size="1" style="width:150px" ', 'value', 'text', $selectID );
	}
	
	/**
	 * Display add item form
	 * */
	function displayAddItems() {		
		$model = & $this->getModel ();
		$data = $model->getFeedItem ();
		$this->assignRef ( "data", $data );
		
		if ($data->FeedID != "0") {
			$MetaData = unserialize ( $data->MetaData );
			foreach ( $MetaData as $key => $val ) {
				if (is_numeric ( $key )) {
					JRequest::setVar ( 'field_id_' . $key, $val );
				} else {
					JRequest::setVar ( $key, $val );
				}
			}
		}
		
		JRequest::setVar ( "FeedID", $data->FeedID );
		
		$SchemaID = JRequest::getVar ( "SchemaID", $data->SchemaID);
		if (empty ( $SchemaID )) {
			$db = & JFactory::getDBO ();
			$db->setQuery ( "SELECT SchemaID FROM #__ja_xml_schemas LIMIT 1" );
			$SchemaID = $db->loadResult ();
		}
		$this->assignRef ( "SchemaID", $SchemaID );
	}
	
	/* Build XML document tree from Schema function*/
	function fcnBuildXMLDocumentTree($schemaID, $elementID=0) {
		static $isPivot;
		static $feedRow;
		global $elementInputOptions;
		static $xmlDepth = 0;
		
		$db =& JFactory::getDBO();
		
		if ($elementInputOptions =='') {
			$elementInputOptions = 'BUTTONS';
		}
	
		$feedID = (int) JRequest::getVar("feed_id");
			
		if ($feedRow==null) { 
			$sql = "SELECT * from #__ja_xml_feeds WHERE feed_id = '".$this->fcnGetStandardSQL($feedID)."' ";
			$db->setQuery($sql);
			$feedRow = $db->loadAssoc();
			$feedRow['MetaData'] = unserialize($feedRow['MetaData']);	
		}
		
		if ($xmlDepth > 100) return;
		
		$sql = "select * from #__ja_xml_schemas_details WHERE `ParentID`='".$this->fcnGetStandardSQL($elementID)."' AND `SchemaID`='".$this->fcnGetStandardSQL($schemaID)."' order by IsParent desc, IsPivot desc ";
		
		$isEnd = false;
		
		$db->setQuery($sql);		
		$result = $db->loadAssocList();
		if ( count($result)>0 ) {
			echo "<br>";
			$isEnd = true;
		}
		
		foreach ( $result as $key=>$row ) {			
			$element = $row['ElementName'];							
			if (isset($feedRow['MetaData']['StaticData_'.$row['ElementID']])) {
				$row['StaticData'] = $feedRow['MetaData']['StaticData_'.$row['ElementID']];
				?>
				 <input type="hidden" name="StaticData_<?php echo $row['ElementID']; ?>" value="<?php echo fcnEscapeHTML($row['StaticData']); ?>"> 
				<?php
			}
	
			if ($row['FieldAttributes']!='') {
				$row['FieldAttributes'] = " ".$row['FieldAttributes'];
			}
			
			$this->fcnPrintSpace($xmlDepth);
			if ($row['IsPivot']=='Y'){
				echo "<b>";
				$isPivot = true;
			}
			
			if(JRequest::getVar("ElementID",'') == $row['ElementID'] || JRequest::getVar("ParentID",'') == $row['ElementID']){
				echo "<span style='background-color:#FFFF33;'>";
			}
			
			// Mandatory tag
			if ($row['IsMandatory']=='Y'){ 
				echo '<font color="red" size="4">*</font>'; 
			}
			
			if ($row['IsMandatory']=='Y' && empty($row['StaticData'])){ 
				echo '<script language="javascript"> arrCheck['.$row['ElementID'].']="'.$row['ElementName'].'"; </script>'; 
			}
			
			echo "<font>&lt;$element</font><font color='blue'>".fcnEscapeHTML($row['FieldAttributes'])."</font><font>&gt;</font>";
			if ($row['IsPivot']=='Y'){
				echo "</b>";
				 echo ' <font color="green">&lt;!-- This item will be iterated for each record (Pivot) --&gt; </font>';
			}
			
			$xmlDepth+=2;
			$ending = $this->fcnBuildXMLDocumentTree($schemaID, $row['ElementID']);
	
			if ($row['IsPivot']=='Y'){
				echo "<b>";
				$isPivot = true;
			}
			
			if ($ending) {				
				if ((($row['StaticData']=='') ||  ($row['StaticMod']!='F')) &&  ($elementInputOptions=='FIELDS') && ($isPivot==true) && ($xmlDepth>=6)) {
					$this->fcnPrintSpace($xmlDepth);
					 ?>
					 <small><input type="checkbox" name="implode_<?php echo $row['ElementID'];?>" value='Y' <?php if ($_REQUEST['implode_'.$row['ElementID']]=='Y') echo ' checked '; ?> ></small> <b>Implode</b> <small>the fields between &lt;<?php echo $element;?>&gt; and &lt;/<?php echo $element;?>&gt; in to one single value</small>
					 <?php
					echo '<br>';
				}
				$this->fcnPrintSpace($xmlDepth);
			} else {	
				if ($elementInputOptions=='FIELDS') {
					if (($row['StaticData']=='') ||  ($row['StaticMod']!='F')) {
						fcnGetSelectField($row, $feedRow);
						if ($row['StaticMod']=='A') {
							echo "<font color='maroon'><b>".$row['StaticData']."</b></font>";
						}
						
						if ($row['IsBoolean']=='Y') {
							?>
							Export as <font color="blue"><b>true</b></font> if data = <input type='text' size='10' name="<?php echo 'boolean_p_'.$row['ElementID']; ?>" value="<?php echo JRequest::getVar('boolean_p_'.$row['ElementID']); ?>" >
							<?php
						}
						 
					}else{
						echo "<font color='maroon'><b>".$row['StaticData']."</b></font>";
					}
				}else{
					echo "<font color='maroon'><b>".$row['StaticData']."</b></font>";
				}			
			}
			echo "<font>&lt;/$element&gt;</font>";
			if(JRequest::getVar("ElementID",'') == $row['ElementID'] || JRequest::getVar("ParentID",'') == $row['ElementID']){
				echo "</span>";
			}
			
			// Show FieldComments
			$FieldComment = ''; $comma='';
			if ($row['IsBoolean']=='Y') { $FieldComment .= '  Boolean'; $comma=',';}
			if ($row['IsCDATA']=='Y') { $FieldComment .= $comma.' CDATA'; $comma=',';}
			if ($row['IsStripTag']=='Y') { $FieldComment .= $comma.' Strip Tags'; $comma=',';}
			if ($row['truncate']>0) { $FieldComment .= $comma.' Truncate to:'.$row['truncate'].' chars'; $comma=',';}
			if ($row['CodeProType']=='Y') { $FieldComment .= $comma.' Export codes as names'; $comma=',';}
			if ($row['CatProType']=='Y') { $FieldComment .= $comma.' Export categories as names'; $comma=',';}
			if ($row['FieldComment']!='') {
				if ($FieldComment) {
					$FieldComment = $FieldComment.",";
				}
				$FieldComment .= " ".$row['FieldComment'];
			}
			if ($FieldComment!='') {
				echo ' <font color="green">&lt;!-- '.$FieldComment.' --&gt;</font> ';
			}
			
			$path = "components/com_jajobboard/asset/";
			if ($elementInputOptions=='BUTTONS') {
				$id = JRequest::getVar("cid", 0, "array");
				$id = $id[0];
				$url = "index.php?option=com_jajobboard&view=jaxmlexport&tab=schemas&task=configxml&cid[]={$id}&";
				echo "&nbsp; <a href='{$url}act=add&SchemaID=".$schemaID."&ParentID=".$row['ElementID']."'><img border=0 src='{$path}add.gif' title='Add new child element'></a>". 			
					" <a href='{$url}act=edit&SchemaID=".$schemaID."&ElementID=".$row['ElementID']."'><img border=0 src='{$path}edit.png'  title='Edit element'></a>".
					" <a  href='{$url}act=delete&SchemaID=".$schemaID."&ElementID=".$row['ElementID']."' onclick=\"if (!confirm('Delete, are you sure?')) return false;\" ><img border=0  title='Delete element' src='{$path}delete.gif' ></a>";
			} 
			echo "<br>";
			if ($row['IsPivot']=='Y'){
				echo "</b>";
				$isPivot = false;
			}
		}
		$xmlDepth-=2;
		return $isEnd;
	}
	
	function fcnPrintSpace ($i) {
		for ($x=0; $x < $i; $x++) {
			echo "&nbsp;&nbsp;";
		}
	}
	
	function fcnGetStandardSQL($str){
		return mysql_real_escape_string($str);
	}
	/**
	 * Display List of categories
	 */
	function displayListSchemas() {
		global $mainframe, $option;
		
		$usergroup = JRequest::getVar ( 'usergroup', 'admin' );		
		$model = & $this->getModel ();
		
		$option_1 = $option . '.jaxmlexport';
		$search = $mainframe->getUserStateFromRequest ( "$option_1.search", 'search', '', 'string' );
		$lists ['search'] = JString::strtolower ( $search );
		
		$lists ['filter_order'] = JRequest::getVar ( 'filter_order', 'u.SchemaID' );
		$lists ['filter_order_Dir'] = $mainframe->getUserStateFromRequest ( $option_1 . '.filter_order_Dir', 'filter_order_Dir', '', 'word' );
		$lists ['option'] = $option;
		$filter_state = $mainframe->getUserStateFromRequest ( $option_1 . '.filter_state', 'filter_state', '', 'word' );
		$lists ['state'] = JHTML::_ ( 'grid.state', $filter_state );
		
		$usertype = '';
		$usertype = $mainframe->getUserStateFromRequest ( $option_1 . $usergroup . '.usertype', 'usertype', '', 'string' );
		
		$items = $model->getSchemas ();
		
		$pagination = & $this->get ( 'Pagination' );
		$this->assignRef ( 'lists', $lists );
		$this->assignRef ( 'items', $items );
		$this->assignRef ( 'usergroup', $usergroup );
		$this->assignRef ( 'pagination', $pagination );
	}
	
	function menu_User() {
		global $option;
		
		$tab = JRequest::getVar ( 'tab', 'feeds' );
		
		?>
			<div class="t">
			<div class="t">
			<div class="t"></div>
			</div>
			</div>
			<div class="m">
			<ul id="submenu">
				<li><a
					href="index.php?option=<?php
					echo $option;
					?>&view=jaxmlexport&tab=feeds"
					class="<?php
					if ($tab == null || $tab == 'feeds')
						echo 'active'?>">
										<?php
					echo JText::_ ( 'XML FEEDS' );
					?>
									</a></li>
				<li><a
					href="index.php?option=<?php
					echo $option;
					?>&view=jaxmlexport&tab=schemas"
					class="<?php
					if ($tab == 'schemas')
						echo 'active'?>">
											<?php
					echo JText::_ ( 'XML SCHEMAS' );
					?>
										</a></li>
			</ul>
			<div class="clr"></div>
			</div>
			<div class="b">
			<div class="b">
			<div class="b"></div>
			</div>
			</div>
			<?php
		}
}
?>